package ch.cm.android.teamlearn.gcm;

import java.sql.SQLException;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import ch.cm.android.teamlearn.R;
import ch.cm.android.teamlearn.R.drawable;
import ch.cm.android.teamlearn.model.Question;
import ch.cm.android.teamlearn.orm.DataBaseHelper;

import com.google.gson.Gson;
import com.j256.ormlite.dao.Dao;

public class QuestionReceiver extends BroadcastReceiver {

    private static String TAG = QuestionReceiver.class.getName();

    @Override
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra("message");
        Gson gson = new Gson();
        Question newQuestion = null;
        if (!message.isEmpty()) {
            newQuestion = gson.fromJson(message, Question.class);
            new NotificationMaker().makeCoolNotification(R.drawable.ic_launcher, "Teamlearn wurde aktualisiert",
                    "Bazzinga", context);
        }

        try {
            Dao<Question, Integer> dao = new DataBaseHelper(context).getDao();
            List<Question> oldQuestions = dao.query(dao.queryBuilder().where().eq("id", newQuestion.id).prepare());

            if (oldQuestions.isEmpty()) {
                dao.create(newQuestion);
            } else {
                updateQuestion(newQuestion, dao, oldQuestions);
            }
        } catch (SQLException e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private void updateQuestion(Question newQuestion, Dao<Question, Integer> dao, List<Question> oldQuestions)
            throws SQLException {
        Question oldQuestion = oldQuestions.get(0);
        oldQuestion.question = newQuestion.question;
        oldQuestion.rightAnswer = newQuestion.rightAnswer;
        oldQuestion.wrongAnswer1 = newQuestion.wrongAnswer1;
        oldQuestion.wrongAnswer2 = newQuestion.wrongAnswer2;
        oldQuestion.tag = newQuestion.tag;
        dao.update(oldQuestion);
    }

}
